package com.koron.plan.web.repairplan.notified;

import com.koron.plan.config.Constants;
import com.koron.plan.web.repairplan.bean.entity.PlanPackageIssueBean;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageIssueVO;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageVO;
import com.koron.plan.web.repairplan.mapper.PlanPackageMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author twcao
 * @title: RepairPlanIssue
 * @projectName GDH_EAM_V2
 * @description: 检修计划下发后的操作
 * @date 2021/9/2314:40
 */
@Component
public class RepairPlanIssue implements RepairPlanNotify<PlanPackageIssueBean> {

    /**
     * 保存之后
     * @param factory 会话
     * @param vo 实体
     * @return 是否成功
     */
    @Override
    public boolean saveAfter(SessionFactory factory, PlanPackageIssueBean vo) {
        PlanPackageMapper mapper = factory.getMapper(PlanPackageMapper.class);
        PlanPackageVO planPackageVO = mapper.queryById(vo.getPackageId());
        if(Objects.isNull(planPackageVO)) {
            // 如果没有检修计划包，说明是创建的计划，无需改变计划包的状态
            return true;
        }
        List<PlanPackageIssueVO> issueVOs = planPackageVO.getDepts().stream().flatMap(row -> row.getIssues().stream()).collect(Collectors.toList());
        //Assert.notEmpty(issueVOs, "检修计划列表不能为空");
        // 计划包中，状态为执行中的数量大于0
        long executeNum = issueVOs.stream().filter(row -> Constants.REPAIR_PACKAGE_ISSUE_STATE.EXECUTE.equals(row.getStatus())).count();
        if(executeNum > 0) {
            planPackageVO.setStatus(Constants.REPAIR_PACKAGE_STATE.EXECUTION);
        }
        // 计划包中，所有计划均已完成
        long finishNum = issueVOs.stream().filter(row -> Constants.REPAIR_PACKAGE_ISSUE_STATE.FINISH.equals(row.getStatus())).count();
        if(issueVOs.size() == finishNum) {
            planPackageVO.setStatus(Constants.REPAIR_PACKAGE_STATE.FINISH);
        }
        mapper.saveOrUpdate(planPackageVO);
        return true;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
